import moment from 'moment';
import { Connection } from 'mongoose';
import { getInstance } from '../../db';
import { accountSchema } from '../../schemas/accountSchema';
import { userRelationSchema } from '../../schemas/userRelationSchema';

// 搜索朋友
export const searchFriend = async (username: string, uid: string) => {
  const db: Connection = await getInstance();

  // 应该把这些获取model的方法统一封装到shcma里面，这样不用重复的写获取函数
  const accountmodel = db.model('accountmodel', accountSchema);

  const result = await accountmodel.find({ 
    $or: [{
      username: { $regex: username, $options: '$i' }, // options $i不区分大小写
    }],
    uid: {
      $ne: uid,
    }
   })

  // console.log(result, '????');

  return result;
}

// 添加好友，先不加好友验证
export const addNewFriend = async (params: IAnyObject) => {
  // 这里真是垃圾代码，操！！！！！！
  const data1 = {
    ...params,
    time: moment().unix(),
    status: 1,
  };

  const data2 = {
    ...params,
    userId: params.fromUser,
    fromUser: params.userId,
    time: moment().unix(),
    status: 1,
  }

  const db: Connection = await getInstance();

  // 应该把这些获取model的方法统一封装到shcma里面，这样不用重复的写获取函数
  const userRelationModel = db.model('userRelationModel', userRelationSchema);

  await userRelationModel.create(data1);
  const result = await userRelationModel.create(data2);

  return result;
}